<!--
 * @Author: Liz.Zheng
 * @Date: 2022-02-07 09:49:47
 * @LastEditTime: 2023-01-05 16:14:45
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 编辑用户楼宇权限
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    title="楼宇权限"
    :maskClosable="true"
    :visible="visible"
    :width="600"
    @close="closeModal"
    :destoryOnClose="true"
  >
    <!-- :body-style="{ paddingBottom: '80px' }" -->
    <a-collapse v-model:activeKey="activePane">
      <a-collapse-panel key="dep" header="所处部门的权限">
        <ChooseHousingResources
          v-if="getListTrigger"
          :getShowList="getListTrigger"
          :checkable="false"
          :userChecked="0"
          :attachDpt="0"
          :showList="sectionCheckedInfo"
          checkType="build"
          @request="$utils.commonRequest"
        />
      </a-collapse-panel>
      <a-collapse-panel key="self" header="实际楼宇权限">
        <a-row :gutter="[0, 12]">
          <a-col :span="24" v-if="!userEdited">
            <a-alert
              message="当前同部门权限，编辑后将自定义权限"
              type="info"
              show-icon
              style="width: 100%"
            />
          </a-col>
          <a-col :span="24" v-if="!showEdit">
            <a-button type="primary" ghost @click="edit"> 编辑权限 </a-button>
          </a-col>
          <a-col :span="24" v-if="showEdit || userEdited">
            <a-card size="small" title="请勾选编辑权限：" v-if="showEdit">
              <template #extra>
                <a-space>
                  <a-button @click="handleCancelEdit"> 取消 </a-button>
                  <a-button type="primary" @click="save" :loading="saveLoading">
                    保存
                  </a-button>
                </a-space>
              </template>
              <ChooseHousingResources
                checkType="build"
                :defaultChecked="{ buildList: checkedBuildList }"
                @request="$utils.commonRequest"
                :userChecked="0"
                :attachDpt="0"
                @getResult="getResult"
              />

            </a-card>
            <a-card size="small" v-else-if="userEdited">
              <ChooseHousingResources
                :getShowList="getListTriggerTwo"
                :checkable="false"
                :userChecked="0"
                :attachDpt="0"
                :showList="userEditedCheckedInfo"
                checkType="build"
                @request="$utils.commonRequest"
              />
            </a-card>
          </a-col>
        </a-row>
      </a-collapse-panel>
    </a-collapse>
  </a-drawer>
</template>

<script>
import {defineComponent, watch, ref, reactive, toRaw, toRefs, onMounted, nextTick} from "vue";
import { message } from "ant-design-vue";
import request from "../../../../common/utils/request";
import { ChooseHousingResources } from "bl-common-vue3";

export default defineComponent({
  name: "",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
    depId: {
      type: [Number, String],
      default: 0,
    },
  },
  components: { ChooseHousingResources },
  setup(props, context) {
    const state = reactive({
      activePane: ["dep", "self"],
      userEdited: false, // 是否编辑过
      showEdit: false,
      saveLoading: false,
      getListTrigger: 0,
      sectionCheckedInfo: {},
      checkedBuildList: [], // 选中的楼宇
      saveData: {},
      getListTriggerTwo: 0,
      userEditedCheckedInfo: {},
      allCheckedBuildList: [],
    });
    const chooseBuilding = ref(null);
    const closeModal = () => {
      context.emit("cancel");
    };

    const edit = () => {
      if (!state.userEdited) {
        state.checkedBuildList = state.allCheckedBuildList;
      }
      state.showEdit = true;
    };

    const save = () => {
      state.saveLoading = true;
      request
        .post("/org", "/user/grantProjectAuth", {
          uid: props.id,
          builds: JSON.stringify(state.saveData),
          needMsg: true,
        })
        .then((res) => {
          message.success(res.msg || "保存成功！");
          getUserVillage().then(() => {
            state.saveLoading = false;
            state.showEdit = false;
          });
        });
    };

    const getDeptVillage = () => {
      request
        .get("/org", "/department/departmentProjectAuth", {
          uid: props.id,
        })
        .then((res) => {
          const { projectBuild } = res;
          let source = {
            buildId: [],
            villageId: [],
          };
          let buildList = [];
          (projectBuild || []).forEach((data) => {
            data.build.forEach((build_id) => {
              source.buildId.push(build_id);
              buildList.push({
                id: build_id,
                village_id: data.id,
              })
            })
            source.villageId.push(data.id);
          })
          state.allCheckedBuildList = buildList;
          state.sectionCheckedInfo = source;
          state.getListTrigger++;
        });
    };

    const getUserVillage = () => {
      return new Promise((resolve, reject) => {
        state.getListTriggerTwo = 0;
        request
          .get("/org", "/user/getBuildBind", {
            uid: props.id,
          })
          .then((res) => {
            const { projectBuild, buildId, villageId } = res.data;
            state.userEdited = projectBuild && projectBuild.length;
            const builds = {
              buildId: [],
              villageId: [],
              projectBuild: [],
            };
            builds.buildId = (buildId || []).map((v) => Number(v));
            builds.villageId = villageId || [];
            builds.projectBuild = projectBuild || [];
            state.saveData = builds;
            state.userEditedCheckedInfo = {
              buildId: builds.buildId,
              villageId: builds.villageId,
            }
            state.getListTriggerTwo++;
            let buildList = [];
            (projectBuild || []).forEach((v) => {
              if (v.build?.length) {
                v.build.forEach((item) => {
                  buildList.push({
                    id: item,
                    village_id: v.id,
                  })
                })
              }
            })
            state.checkedBuildList = buildList;
            resolve();
          });
      })
    };

    const getResult = (info) => {
      const { villageList, buildList } = info;
      const builds = {
        buildId: [],
        villageId: [],
        projectBuild: [],
      };
      if (villageList.length) {
        for (let village of villageList) {
          builds.buildId = [...builds.buildId, ...(village.buildList.map((v) => v.id))];
          builds.villageId.push(village.id);
          builds.projectBuild.push({
            id: village.id,
            build: village.buildList.map((v) => v.id),
          })
        }
      }
      if (buildList.length) {
        buildList.forEach((item) => {
          builds.buildId.push(item.id);
          if (builds.projectBuild.find((v) => v.id == item.village_id)) {
            builds.projectBuild.find((v) => v.id == item.village_id).build.push(item.id);
          } else {
            builds.projectBuild.push({
              id: item.village_id,
              build: [item.id],
            });
          }
          if (!builds.villageId.includes(item.village_id)) {
            builds.villageId.push(item.village_id);
          }
        })
      }
      state.saveData = builds;
    };

    const handleCancelEdit = () => {
      // 取消编辑
      state.showEdit = false;
    };

    const init = () => {
      getDeptVillage();
      getUserVillage();
    };
    const reset = () => {
      state.showEdit = false;
      state.saveLoading = false;
      state.userEdited = false;
      state.getListTrigger = 0;
      state.sectionCheckedInfo = {};
      state.checkedBuildList = [];
      state.saveData = {};
      state.getListTriggerTwo = 0;
      state.userEditedCheckedInfo = {};
      state.allCheckedBuildList = [];
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          reset();
        }
      }
    );
    return {
      chooseBuilding,
      ...toRefs(state),
      closeModal,
      save,
      edit,
      getResult,
      handleCancelEdit,
    };
  },
});
</script>
